#include "socks5.h"
#include "conn.h"

struct tunnel_conn *tunnel_conn_new()
{
    struct tunnel_conn *conn = (struct tunnel_conn *)malloc(sizeof(struct tunnel_conn));
    if (NULL == conn) {
        return NULL;
    }

    memset(conn, 0, sizeof(struct tunnel_conn));
    conn->stage = SOCKS5_CONN_STAGE_EXMETHOD;

    conn->remote_conn.bndaddr = buffer_new(SOCKS5_DEFAULT_BUFFER_SIZE);
    if (NULL == conn->remote_conn.bndaddr) {
        goto _clean;
    }

        return conn;
_clean:
        if (conn) {
                tunnel_conn_close(conn);
        }
        return NULL;
}

void tunnel_conn_close(struct tunnel_conn *conn)
{
    conn->stage = SOCKS5_CONN_STAGE_CLOSED;

    if (conn->client && hio_fd(conn->client)) {
                hio_close(conn->client);
    }

    if (conn->remote && hio_fd(conn->remote)) {
                hio_close(conn->remote);
    }

    if (conn->remote_conn.bndaddr) {
        buffer_free(conn->remote_conn.bndaddr);
    }
    free(conn);
}

void tunnel_conn_setstage(struct tunnel_conn *conn, uint8_t stage)
{
    LOGD("change stage from [%d] to [%d]\n", conn->stage, stage);
    conn->stage = stage;
}

